package org.wheel.plugins.toolkit.sequence.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.wheel.plugins.toolkit.cache.core.SequenceTemplate;
import org.wheel.plugins.toolkit.cache.spi.SequenceFormatter;
import org.wheel.plugins.toolkit.sequence.annotation.SequenceKey;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Aspect
@Component
public class SequenceAspect {

    private final SequenceTemplate sequenceTemplate;
    private final Map<String, SequenceFormatter> formatters;

    public SequenceAspect(SequenceTemplate sequenceTemplate, List<SequenceFormatter> formatterList) {
        this.sequenceTemplate = sequenceTemplate;
        this.formatters = formatterList.stream()
                .collect(Collectors.toMap(f -> f.getClass().getSimpleName(), f -> f));
    }

    @Around("@annotation(sequenceKey)")
    public Object around(ProceedingJoinPoint joinPoint, SequenceKey sequenceKey) throws Throwable {
        String key = sequenceKey.value();
        if (sequenceKey.useDatePrefix()) {
            key = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE) + ":" + key;
        }
        String seq = sequenceTemplate.nextIdStr(key, sequenceKey.width());
        // 把序列号塞进第一个 String 参数
        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof String) {
                args[i] = seq;
                break;
            }
        }
        return joinPoint.proceed(args);
    }

}